package qingyu.ai.ui.safe.login;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.vondear.rxtools.view.RxToast;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import qingyu.ai.R;
import qingyu.ai.base.BaseEditTextListener;
import qingyu.ai.common.Constants;
import qingyu.ai.common.net.APIFactory;
import qingyu.ai.common.net.NetRequestAdapter;
import qingyu.ai.common.net.NetworkRequestCalback;
import qingyu.ai.common.net.RetrofitHttpUtil;
import qingyu.ai.common.util.EncryptUtil;
import qingyu.ai.common.util.RegexUtils;
import qingyu.ai.common.util.SPUtil;
import qingyu.ai.domain.UserInfoData;
import qingyu.ai.ui.safe.forget.ForgetActivity;
import qingyu.ai.ui.safe.registe.RegisterActivity;

public class LoginActivity extends AppCompatActivity implements NetworkRequestCalback<UserInfoData>, IUiListener {

    @BindView(R.id.edittext_mobile)
    TextInputLayout edittextMobile;
    @BindView(R.id.editext_password)
    TextInputLayout editextPassword;
    @BindView(R.id.btn_login)
    Button btnLogin;
    @BindView(R.id.btn_forget_password)
    Button btnForgetPassword;
    @BindView(R.id.iv_weichat)
    ImageView ivWeichat;
    @BindView(R.id.qq_login)
    ImageView qqLogin;
    private Tencent mTencent;
    private ProgressDialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initQQLogin();
        ButterKnife.bind(this);
        initListener();
    }

    public void showDialog() {
        dialog =
                ProgressDialog.show(this, "提示", "正在登陆中", false);
        dialog.setCancelable(false);
        dialog.show();
    }

    public void closeDialog() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        edittextMobile.getEditText().setText(SPUtil.getString(Constants.userinfo.account, ""));
    }

    private void initListener() {
        edittextMobile.getEditText().addTextChangedListener(new BaseEditTextListener() {
            @Override
            public void afterTextChanged(Editable s) {
                super.afterTextChanged(s);
                edittextMobile.setError(null);
            }
        });
        editextPassword.getEditText().addTextChangedListener(new BaseEditTextListener() {
            @Override
            public void afterTextChanged(Editable s) {
                super.afterTextChanged(s);
                if (!RegexUtils.isEnOrNum(s.toString()))
                    editextPassword.setError(getString(R.string.password_rule));
                else
                    editextPassword.setError(null);
            }
        });
    }

    @OnClick({R.id.iv_back, R.id.btn_login, R.id.btn_register, R.id.btn_forget_password, R.id.iv_weichat, R.id.qq_login})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();//返回上一页
                break;
            case R.id.btn_login://登陆
                login();
                break;
            case R.id.btn_register://注册新账号
                startActivity(new Intent(this, RegisterActivity.class));
                break;
            case R.id.btn_forget_password://忘记密码
                startActivity(new Intent(this, ForgetActivity.class));
                break;
            case R.id.iv_weichat://微信登陆
                break;
            case R.id.qq_login://QQ 登陆
                loginForQQ();
                break;
        }
    }

    private void login() {
        showDialog();
        String account = edittextMobile.getEditText().getText().toString().trim();
        String password = editextPassword.getEditText().getText().toString().trim();
        if (!validate(account, password)) return;//本地验证失败
        String passwordEncrypt = EncryptUtil.encryptMD5ToString(password).toLowerCase();
        HashMap<String, String> map = new HashMap<>();
        map.put("account", account);
        map.put("password", passwordEncrypt);
        new APIFactory(this, RetrofitHttpUtil.BASE_URL)
                .login(map, new NetRequestAdapter<UserInfoData>(this));
    }


    /**
     * 验证账号和密码规则
     *
     * @param account
     * @param password
     * @return
     */
    private boolean validate(String account, String password) {
        if (!RegexUtils.isMobileExact(account) && !RegexUtils.isEmail(account)) {
            edittextMobile.setError(getString(R.string.input_account_error));
            return false;
        }
        edittextMobile.setError(null);
        if (password.length() < 9 || !RegexUtils.isEnOrNum(password)) {
            editextPassword.setError(getString(R.string.password_rule));
            return false;
        }
        editextPassword.setError(null);
        return true;
    }


    @Override
    public void onSuccess(UserInfoData data) {
//        RxToast.success("登陆成功");
        UserInfoData.MemberBean member = data.getMember();
        UserInfoData.ResultBean result = data.getResult();
        if (result != null) {
            String access_token = result.getAccess_token();
            String refresh_token = data.getResult().getRefresh_token();
            SPUtil.putString(Constants.userinfo.access_token, access_token);
            SPUtil.putString(Constants.userinfo.refresh_token, refresh_token);
        }
        if (member != null) {
            String account = member.getAccount();
            String iconUrl = member.getAvatar();
            String nickname = member.getNickname();
            SPUtil.putString(Constants.userinfo.account, account);
            SPUtil.putString(Constants.userinfo.nickname, nickname);
            SPUtil.putString(Constants.userinfo.iconUrl, iconUrl);
        }
        closeDialog();
        finish();
    }

    @Override
    public void onError(int errorCode, String erorMsg) {
        Log.e("xixi", errorCode + "--" + erorMsg);
        closeDialog();
        RxToast.error(erorMsg);
        btnLogin.setEnabled(true);
    }

    @Override
    public void onNetStart() {
        btnLogin.setEnabled(false);
//        RxToast.normal("正在登陆中....");
        Log.e("xixi", "start" + Thread.currentThread());
    }

    @Override
    public void onNetFinish() {
        btnLogin.setEnabled(true);
        Log.e("xixi", "Finish" + Thread.currentThread());

    }

    public void loginForQQ() {
        if (mTencent != null && !mTencent.isSessionValid()) {
            mTencent.login(this, "all", this);
        }
    }


    private void initQQLogin() {
        mTencent =
                Tencent.createInstance(getString(R.string.qq_appid), this.getApplicationContext());
    }


    /**
     * QQ兼容低配机
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.e("xixi", "-->onActivityResult " + requestCode + " resultCode=" + resultCode);
        if (requestCode == com.tencent.connect.common.Constants.REQUEST_LOGIN ||
                requestCode == com.tencent.connect.common.Constants.REQUEST_APPBAR) {
            Tencent.onActivityResultData(requestCode, resultCode, data, this);
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * QQ Login
     *
     * @param data
     */
    @Override
    public void onComplete(Object data) {
        Log.e("xixi", data.toString());
        try {
            if (data == null) {
                RxToast.error("QQ授权登陆失败，请重新登陆！");
                return;
            }
            showDialog();
            JSONObject dataJson = new JSONObject(data.toString());
            if (dataJson != null && dataJson.length() == 0)
                RxToast.error("QQ授权登陆失败，请重新登陆！");
            String access_token = dataJson.getString("access_token");
            String openid = dataJson.getString("openid");
            Map<String, String> map = new HashMap<>();
            map.put("access_token", access_token);
            map.put("openid", openid);
            new APIFactory(this,RetrofitHttpUtil.BASE_URL)
                    .qqLogin(map, new NetRequestAdapter<UserInfoData>(this));
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    /**
     * QQ Login
     *
     * @param uiError
     */
    @Override
    public void onError(UiError uiError) {
        Log.e("xixi", uiError.errorMessage + "----" + uiError.errorCode + "---" + uiError.errorDetail);
        RxToast.error("登陆失败");
    }

    /**
     * QQ Login
     */
    @Override
    public void onCancel() {
        Log.e("xixi", "cancel");
        RxToast.normal("取消登陆");
    }
}
